<?php

//tailvh@gmail.com
require_once ROOT_APPLICATION_MODULES_ADMIN_MODELS . DS . "Users.php";

class Admin_AuthController extends Zend_Controller_Action {

    private $modelUser;

    public function init() {
        $this->modelUser = new End_Models_Users();
        
        $layoutPath = APPLICATION_PATH . '/templates/admin/default';
        $option = array('layout' => 'index',
            'layoutPath' => $layoutPath);

        Zend_Layout::startMvc($option);
    }

    public function loginAction() {
        $_LOGIN['username'] = 'Admin';
        $_LOGIN['password'] = '';
        //Delete session
        if (isset($_SESSION['links']))
            unset($_SESSION['links']);

        //$news = $this->modelsNews->_filter('6', '1');

        if ($this->getRequest()->isPost()) {
            $username = $_POST['username'];
            $password = $_POST['password'];

            if (isset($username) && isset($password)) {

                if ($this->loginProcess($username, $password)) {

                    $this->_redirect('admin/index');
                } else {
                    $this->_redirect('admin/auth/login');
                }
            }
            //$this->view->news = $news;
            $this->_redirect('admin/index');
        }
    }

    public function logoutAction() {
        $storage = new Zend_Auth_Storage_Session();
        $storage->clear();
        $this->logoutProcess();

        $this->_redirect('admin/auth/login');
    }

    private function logoutProcess() {
        try { 
            Zend_Auth::getInstance()->clearIdentity();
            $this->_redirect('admin/index');
        } catch (Zend_Ldap_Exception $ex) {
            $logger = Zend_Registry::get('Zend_Log');
            $logger->log($ex->getMessage(), Zend_Log::ERR);
        } catch (Exception $ex) {
            $logger = Zend_Registry::get('Zend_Log');
            $logger->log($ex->getMessage(), Zend_Log::ERR);
        }
    }

    protected function _getAuthAdapter() {

        $dbAdapter = Zend_Db_Table::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

        $authAdapter->setTableName('core_user')
                ->setIdentityColumn('user_name')
                ->setCredentialColumn('password');

        return $authAdapter;
    }

    private function loginProcess($username, $password) {
        try {
            if ($this->onlyLoginProcess($username, $password)) {

                // Get our authentication adapter and check credentials
                $adapter = $this->_getAuthAdapter();
                $adapter->setIdentity($username);
                $adapter->setCredential($password);

                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($adapter);

                if ($result->isValid()) { 
                    $user = $adapter->getResultRowObject();
                    $auth->getStorage()->write($user);
                   
                    return true;
                }
                return false;
            }
        } catch (InvalidArgumentException $ex) {
            $logger = Zend_Registry::get('Zend_Log');
            $logger->log($ex->getMessage(), Zend_Log::ERR);
        } catch (Exception $ex) {
            $logger = Zend_Registry::get('Zend_Log');
            $logger->log($ex->getMessage(), Zend_Log::ERR);
        }
    }

    private function onlyLoginProcess($username, $password) {
        try {
            $arrUser = $this->modelUser->_filter('user_name = ?', $username);
            $user = $arrUser[0];
            if ($user->password == $password)
                return true;
            else
                return false;
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    public static function signup($data) {
        $modelsUsers = new Models_Users();

        if ($this->getRequest()->isPost()) {
            if ($data['password'] != $data['confirmPassword']) {
                $this->view->errorMessage = "Password and confirm password don't match.";
                return;
            }
            $username = $data['username'];
            $result = $modelsUsers->_fillter("username = $username", null, null);
            if ($result) {
                $this->view->errorMessage = "Name already taken. Please choose another one.";
                return;
            }
            unset($data['confirmPassword']);
            $objData = Utility_Converter::arrayToObject($data);
            $modelsUsers->_insert($objData);
        }
    }

}
